package GUI;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;

import javax.swing.AbstractButton;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

import CommonGui.LengthFilter;
import DataObjects.Bon;
import DataObjects.Menu;
import DataObjects.MetaDataOrder;
import Messages.MessageCheckExistsEmpForClockInOut;
import Messages.MessageCheckExistsEmpForClockInOutReply;
import Messages.MessageGetAllMenues;
import Messages.MessageGetAllMenuesReply;

import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.swing.JLabel;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;
import javax.swing.text.DocumentFilter.FilterBypass;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

public class PfOpenTable extends JPanel{
	
	private Dimension screenSize;
	
	private MainMenu mainMenu;
	private Vector<Menu> menues;
	private Vector<Bon> bones;
	private JTextField textField;
	private JTextField textFieldNumPersons;
	private JTextField textFieldNumChild;
	private String tableNo;
	private MetaDataOrder metaDataOrder;
	private int x;
	private int y;
	private JLabel waiterName;
	private int numOfPersons=(-1);
	private int focusFlag=0;
	
	public PfOpenTable (MainMenu mm, Vector<Menu> m,Vector<Bon> vector,String tableNo)
	{
		super();
		setBackground(new Color(250, 250, 210));
		screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		this.mainMenu=mm;
		this.menues=m;
		this.bones=vector;
		this.tableNo=tableNo;
		this.setLayout(null);
		initialize();
		
			SwingUtilities.invokeLater(new Runnable(){
			    public void run(){
			    	
					textField.grabFocus();
			    }
			});
		
		
		
	
		textField.setVisible(true);
		textField.setFocusable(true);
		textField.grabFocus();
	}
	
	
	private void initialize()
	{
		x=screenSize.width;
		y=screenSize.height;
		final VKBDigitsOnly vkbPanel=new VKBDigitsOnly(new Color(200,250,230));                                                                    
		vkbPanel.setBounds(4*x/8, y/5, 6*x/22, 2*y/5);
		add(vkbPanel);
		
		//--- textField for waiter number
		textField = new JTextField();			
		textField.setHorizontalAlignment(JTextField.RIGHT);
		textField.setFont(new Font("Tahoma", Font.PLAIN, 20));
		AbstractDocument doc = (AbstractDocument) textField.getDocument();
		doc.setDocumentFilter(new LengthFilter(doc.getLength(), 4));
		textField.setBounds(x/5, y/4, x/12, y/20);
			
		textField.getDocument().addDocumentListener(new DocumentListener() {

			@Override
			public void changedUpdate(DocumentEvent arg0) {
				
				
			}

			@Override
			public void insertUpdate(DocumentEvent arg0) {
				Document temp=arg0.getDocument();
				int size=temp.getLength();
				String currText=null;
				int num=0;
				
				try {
					currText=temp.getText(0, size);
				} catch (BadLocationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
				try {
					 num=Integer.parseInt(currText);
				  } catch (NumberFormatException e) {
					  JOptionPane.showMessageDialog(null,"מספר לא תקין");
				  }
				
				if(size==4 && num!=0)         //if the input includes 4 digits we will display the name of the waiter on the screen 
				{
					MessageCheckExistsEmpForClockInOut msgCheck=new MessageCheckExistsEmpForClockInOut(currText);
					try {
						mainMenu.ms.client.sendToServer(msgCheck);
						MessageCheckExistsEmpForClockInOutReply result = (MessageCheckExistsEmpForClockInOutReply)mainMenu.ms.client.GetMessage();
						String name=result.getUserName();
						if(!name.equals("null"))
						{
						setNameOnTheScreen(name);
						textFieldNumPersons.grabFocus();
						}
						
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
				else
				{
					hindNameOnTheScreen();
				}
			}

			@Override
			public void removeUpdate(DocumentEvent arg0) {				
				
			}			
		});
		
		
		add(textField);
		
		
		
		
		//--- textField for num of persons
		textFieldNumPersons = new JTextField();
		textFieldNumPersons.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		textFieldNumPersons.setFont(new Font("Tahoma", Font.PLAIN, 20));
		textFieldNumPersons.setBounds(x/5, 10*y/30, x/12, y/20);
		AbstractDocument doc2 = (AbstractDocument) textFieldNumPersons.getDocument();
		doc2.setDocumentFilter(new LengthFilter(doc2.getLength(), 3));
		add(textFieldNumPersons);
		textFieldNumPersons.setColumns(10);
		
		//---textField for num of children
		textFieldNumChild = new JTextField("0");
		textFieldNumChild.setForeground(new Color(192, 192, 192));		
		textFieldNumChild.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		textFieldNumChild.setCaretPosition(textFieldNumChild.getText().length());
		textFieldNumChild.setFont(new Font("Tahoma", Font.PLAIN, 20));
		textFieldNumChild.setBounds(x/5,10*y/25, x/12, y/20);
		AbstractDocument doc3 = (AbstractDocument) textFieldNumChild.getDocument();
		doc3.setDocumentFilter(new LengthFilter(doc3.getLength(), 3));
		add(textFieldNumChild);
		textFieldNumChild.setColumns(10);
		textFieldNumChild.addFocusListener(new FocusListener() {
		      public void focusGained(FocusEvent e) {	    
		        JTextField text=(JTextField) e.getSource();
			  	text.setForeground(new Color(0, 0, 0));
		        if(text.getText().equals("0") && focusFlag==0)
		        {
		        	text.setText("");
		        	focusFlag=1;
		        }
		        else
		        {
		        	text.setForeground(new Color(0, 0, 0));
		        }
		      }

		      public void focusLost(FocusEvent e) {
		      JTextField text=(JTextField)e.getSource();
		      if(text.getText().isEmpty())
		      {
		    	text.setText("0");
		  		text.setForeground(new Color(192, 192, 192));
		    	focusFlag=0;
		      }
		      else
		      {
		  		text.setForeground(new Color(0, 0, 0));
		      }		        
		      }
		    });
		
		
		
		//----------------------------------------------- create button ok (פתיחה)
		
		Icon okIcon = new ImageIcon("ok-icon.png");
		Image img = ((ImageIcon) okIcon).getImage();
		Image newimg = img.getScaledInstance(40, 40,
				java.awt.Image.SCALE_SMOOTH);
		okIcon = new ImageIcon(newimg);
		JButton btnNewButton = new JButton("פתיחה", okIcon);
		btnNewButton.setVerticalTextPosition(AbstractButton.BOTTOM);
		btnNewButton.setHorizontalTextPosition(AbstractButton.CENTER);
		btnNewButton
				.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, x/85));
		btnNewButton.setBounds(7*x/18, 10*y/19, x/11, y/12);
		//btnNewButton.setPreferredSize(new Dimension(110, 90));
		btnNewButton.addActionListener(new java.awt.event.ActionListener() 
		   {
			public void actionPerformed(java.awt.event.ActionEvent e) 
			{
				String inputEid=textField.getText();
				try
				{
					numOfPersons=Integer.parseInt(textFieldNumPersons.getText());
				}catch(NumberFormatException e1)
				{
					numOfPersons=-1;
					JOptionPane.showMessageDialog(null,"מספר הסועדים לא תקין");
				}
				
				
				MessageCheckExistsEmpForClockInOut msgCheck=new MessageCheckExistsEmpForClockInOut(inputEid);
				try {
					mainMenu.ms.client.sendToServer(msgCheck);
					MessageCheckExistsEmpForClockInOutReply result = (MessageCheckExistsEmpForClockInOutReply)mainMenu.ms.client.GetMessage();
					String name=result.getUserName();
					if(name.equals("null")==false && numOfPersons>-1)
					{
						metaDataOrder=new MetaDataOrder();
						metaDataOrder.setEid(inputEid);
						metaDataOrder.setName(name);
						metaDataOrder.setTid(tableNo);
						metaDataOrder.setNew(true);
						metaDataOrder.setNumOfPersons(numOfPersons);
						metaDataOrder.setNumOfChild(Integer.parseInt(textFieldNumChild.getText()));
						DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
						DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");

						
						Date date = new Date();
						String orderDate=dateFormat.format(date);
						String orderTime=timeFormat.format(date);
						metaDataOrder.setDate(orderDate);
						metaDataOrder.setTime(orderTime);
						mainMenu.getContentPane().remove(((BorderLayout)mainMenu.getContentPane().getLayout()).getLayoutComponent(BorderLayout.CENTER));
						//mainMenu.getContentPane().add(new PfPtihatShulhanLeftRigtPanels(mainMenu,menues,bones,metaDataOrder), BorderLayout.CENTER);					
						mainMenu.getContentPane().add(new PfUpdateTableOrder(mainMenu,menues,bones,metaDataOrder,null), BorderLayout.CENTER);					

						mainMenu.getContentPane().validate();
					}
					else
					{
						if(name.equals("null")==true)
						{
						JLabel label_2 = new JLabel("מספר עובד לא תקין");                       
						label_2.setBounds(3*x/14, 5*y/11, x/4, y/15);
						label_2.setFont(new Font("Tahoma", Font.BOLD, x/54));
						label_2.setForeground(Color.red);
						add(label_2);
						mainMenu.getContentPane().repaint();
						}
					}
				
				} catch (IOException ei) {
					// TODO Auto-generated catch block
					ei.printStackTrace();
				}		
				
								
			}
		});
		add(btnNewButton);
		
		
		
		
		
		//----------------------------------------------- create button cancel (ביטול)
		
				Icon cancelIcon = new ImageIcon("cancel-icon.png");
				Image imgcancel = ((ImageIcon) cancelIcon).getImage();
				Image newimgcancel = imgcancel.getScaledInstance(40, 40,
						java.awt.Image.SCALE_SMOOTH);
				cancelIcon = new ImageIcon(newimgcancel);
				JButton btnNewButton_1 = new JButton("ביטול", cancelIcon);
				btnNewButton_1.setVerticalTextPosition(AbstractButton.BOTTOM);
				btnNewButton_1.setHorizontalTextPosition(AbstractButton.CENTER);
				btnNewButton_1
						.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, x/85));
				btnNewButton_1.setBounds(7*x/100, 10*y/19, x/11, y/12);
				btnNewButton_1
				.addActionListener(new java.awt.event.ActionListener() {
					public void actionPerformed(java.awt.event.ActionEvent e) {
						mainMenu.getContentPane().remove(((BorderLayout) mainMenu.getContentPane().getLayout()).getLayoutComponent(BorderLayout.EAST));
						//for kill thread
						((BorderLayout) mainMenu.getContentPane().getLayout()).getLayoutComponent(BorderLayout.CENTER).setVisible(false);
						//////////////////////
						mainMenu.getContentPane().remove(((BorderLayout) mainMenu.getContentPane().getLayout()).getLayoutComponent(BorderLayout.CENTER));
						mainMenu.getContentPane().add(new PfScheem_All_Tables(mainMenu),BorderLayout.CENTER);
						mainMenu.getContentPane().add(new PanelFunctionsTables(mainMenu),BorderLayout.EAST);
						mainMenu.getContentPane().validate();

					}
				});
				add(btnNewButton_1);
		
		
		//--------------------------------------create ptihat shulhan label
		JLabel label = new JLabel("פתיחת שולחן : "+tableNo);    //ptihat shulhan
		label.setForeground(new Color(47, 79, 79));
		label.setFont(new Font("Tahoma", Font.BOLD, x/48));
		label.setBounds(x/5, y/8, x/4, y/13);
		add(label);
		
		JLabel label_1 = new JLabel("\u05DE\u05E1' \u05DE\u05DC\u05E6\u05E8 : ");                       //mispar miltsar
		label_1.setBounds(5*x/16, 3*y/11, x/10, y/50);
		label_1.setFont(new Font("Tahoma", Font.BOLD, x/68));
		add(label_1);
		
		
		JLabel label_2 = new JLabel("מס' מבוגרים : ");                       
		label_2.setBounds(5*x/16, 5*y/14, x/8, y/50);
		label_2.setFont(new Font("Tahoma", Font.BOLD, x/68));
		add(label_2);
		
		JLabel label_3 = new JLabel("מס' ילדים : ");                       
		label_3.setBounds(5*x/16, 5*y/12, x/8, y/50);
		label_3.setFont(new Font("Tahoma", Font.BOLD, x/68));
		add(label_3);
		
		
		
		//---------------------------------------create name of waiter label
		waiterName= new JLabel();
		waiterName.setBounds(5*x/50, 3*y/11, x/9, y/15);
		waiterName.setFont(new Font("Tahoma", Font.BOLD, x/35));
		waiterName.setForeground(Color.blue);
		waiterName.setVisible(false);
		add(waiterName);
		
	}
	
	
		
		
	
	
	private void setNameOnTheScreen(String name)
	{
		//String name2="איגור";
		//waiterName.setName(name2);
		if(name.equals("null")==false)
		{
		waiterName.setText(name);		
		waiterName.setVisible(true);
		}
	}
	
	
	private void hindNameOnTheScreen()
	{
	    waiterName.setVisible(false);
	}
	
	
	
	
}
